package org.jgs1904.apachepoidemo.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * @author: 默苍璃
 * @date: 2023-10-09 18:25
 */
@Component
public class ExcelImportExample {

    public void excelImportExample(HttpServletRequest request) throws IOException {
        // 获取请求的输入流
        InputStream excelInputStream = request.getInputStream();

        // 创建工作簿并加载 Excel 文件
        Workbook workbook = new XSSFWorkbook(excelInputStream);

        // 获取第一个表格
        Sheet sheet = workbook.getSheetAt(0);

        // 遍历表格中的行和单元格，并获取数据
        for (Row row : sheet) {
            for (Cell cell : row) {
                String cellValue = "";
                // 根据单元格类型获取数据
                switch (cell.getCellType()) {
                    case STRING:
                        cellValue = cell.getStringCellValue();
                        break;
                    case NUMERIC:
                        cell.setCellType(CellType.STRING);
                        cellValue = cell.getStringCellValue();
                        break;
                    case BOOLEAN:
                        cellValue = String.valueOf(cell.getBooleanCellValue());
                        break;
                    // 其他类型可以根据需要进行处理
                }
                System.out.print(cellValue + "\t");
            }
            System.out.println();
        }

        // 关闭文件输入流
        excelInputStream.close();

        System.out.println("Excel 文件已成功导入。");
    }

}
